package com.ljh.SimpleTradingSystem.controller;

import com.ljh.SimpleTradingSystem.mybatis.entity.Message;
import com.ljh.SimpleTradingSystem.mybatis.mapper.MessageMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/message")
public class MessageController {
    @Resource
    MessageMapper messageMapper;

    @GetMapping("")
    @ResponseBody
    public List<Message> getMessage(@RequestParam int senderId, @RequestParam int receiverId) {
        List<Message> messageList = messageMapper.selectBySenderIdAndReceiverId(senderId, receiverId);
        return messageList;
    }

    @GetMapping("/{id}")
    @ResponseBody
    public List<Message> getMessageById(@PathVariable int id) {
        List<Message> messageList = messageMapper.selectById(id);
        return messageList;
    }

    @PostMapping("")
    @ResponseBody
    public String addMessage(@RequestParam int senderId, @RequestParam int receiverId, @RequestParam String text) {
        Date time = new Date();
        String messageTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(time);

        Message message = new Message(senderId, receiverId, text, messageTime);
        messageMapper.insert(message);
        return "success";
    }
}
